import { createStore } from 'vuex'
import Cookies from 'js-cookie'
export default createStore({
  state: {
    isCollapse: true,
    currentMenu: null,
    menu: [],
    token: ''
  },
  mutations: {
    updateIsCollapse(state, payload) {
      state.isCollapse = !state.isCollapse
    },
    selectMenu(state, val) {
      //判断
      val.name == 'home' ? state.currentMenu == null : (state.currentMenu = val)
    },
    setMenu(state, val) {
      state.menu = val
      localStorage.setItem('menu', JSON.stringify(val))
    },
    addMenu(state, router) {
      if (!localStorage.getItem('menu')) {
        return
      }
      const menu = JSON.parse(localStorage.getItem('menu'))
      state.menu = menu

      // const menuArray = []

      // menu.forEach((item) => {
      //   if (item.children) {
      //     item.children = item.children.map((item) => {
      //       let url = `../views/${item.url}.vue`
      //       item.component = () => import(url)
      //       return item
      //     })
      //     menuArray.push(...item.children)
      //   } else {
      //     let url = `../views/${item.url}.vue`
      //     item.component = () => import(url)
      //     menuArray.push(...item.children)
      //   }
      // })
      // menuArray.forEach((item) => {
      //   router.addRoute('home', item)
      // })
    },

    cleanMenu(state) {
      state.menu = []
      localStorage.removeItem('menu')
    },
    setToken(state, val) {
      state.token = val
      Cookies.set('token', val)
    },
    clearToken() {
      state.token = ''
      Cookies.remove('token')
    },
    getToken(state) {
      state.token = state.token || Cookies.get('token')
    }
  }
})
